<script setup>
import { ref } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import appStore from '@/store'
import router from '@/router'
import LoginApi from '@/service/api/login/login'
//导入用户仓库
const { setToken } = appStore.useUser
// 登录
const login = async () => {
  await form.value.validate()
  const res = await LoginApi.login(formModel.value)
  console.log(res)
  if (res.code !== 200) {
    ElMessage.error(res.msg)
  }
  //传入注册表单内容，获取token
  if (res.code === 200) {
    ElMessage.success('登录成功')
    //把token存在仓库
    console.log(res.data.token)
    setToken(res.data.token)
    //查看是否存入成功
    router.push('/')
  }
}
// setToken(res.data.token)

// //使用api获取信息
// await form.value.validate()
// try {
//   const res = await userLoginService(formModel.value)
//   console.log(res)
//   if (res.code !== 200) {
//     ElMessage.error(res.msg)
//   }
//   //传入注册表单内容，获取token
//   if (res.code === 200) {
//     ElMessage.success('登录成功')
//     //把token存在仓库
//     setToken(res.data.token)
//     //查看是否存入成功
//     router.push('/')
//   }
// } catch (err) {
//   console.log(err)
// }

// 注册
const register = async () => {
  await form.value.validate()
  const res = await LoginApi.register(formModel.value)
  console.log(res)
  if (res.code !== 200) {
    ElMessage.error(res.msg)
  }
  if (res.code === 200) {
    ElMessage.success('注册成功')
  }

  // setToken(res.data.token)
  router.push('/')
}
//const isRegister = ref(false)

const form = ref()

//整个用于提交的数据对象
const formModel = ref({
  account: '',
  password: '',
  rePassword: '',
  name: '',
  work_num: ''
})

//整个表单校验规则
//1.非空校验
//2.长度校验
//3.正则校验 pattern
//4.自定义校验 validator => (rule value callback)
const rules = {
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' }, //最后一句是指失焦时校验,change是改变校验
    { min: 5, max: 10, message: '用户名必须是 5-10位 的字符', trigger: 'blur' } //长度校验
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      //正则校验
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位非空字符',
      trigger: 'blur'
    }
  ],
  rePassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      //正则校验
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位非空字符',
      trigger: 'blur'
    },
    {
      //自定义校验 必须与 password相同
      validator: (rule, value, callback) => {
        if (value !== formModel.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }
    }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名必须是 2-10位 的字符', trigger: 'blur' } //长度校验
  ],
  work_num: [
    { required: true, message: '请输入工号', trigger: 'blur' },
    { min: 5, max: 12, message: '工号必须是 5-12位 的字符', trigger: 'blur' } //长度校验
  ]
}
// 登录注册判断
const isRegister = ref(true)
</script>

<template>
  <!-- 
    1.结构相关
        el-row表示一行，一行分成24份
        el-col表示列
        (1):span='12' 表示在一行中，占12份（50%）
        (2):pan='6'   表示在一行中，占6份（25%）
        (3):offset="3"  代表在一行中，左侧margin份数

        el-form 整个表单组件
        el-form-item 表单的一行（一个表单域）
        el-input 表单元素（输入框） 
    2.校验相关
    （1）el-from => :model ="ruleFrom",绑定整个表单的数据对象       
    （2）el-from => :rules = "rules"，绑定rules的规则对象
    (3)表单元素 => v-model = "ruleFrom.xxx"给表单元素，绑定from的子属性
    （4）el-item => prop配置生效的是哪个校验规则（和rules中的字段要对应）
     -->
  <el-row class="login-page">
    <el-col :span="8" :offset="8">
      <!-- 登陆相关表单 -->
      <el-form
        v-if="isRegister"
        ref="form"
        :model="formModel"
        :rules="rules"
        size="large"
        autocomplete="off"
        class="form"
      >
        <!-- v-else -->
        <el-form-item class="title">
          <div>
            <h1>欢迎登录</h1>
          </div>
        </el-form-item>
        <div class="form-data">
          <el-form-item prop="account" class="input">
            <el-input
              v-model="formModel.account"
              :prefix-icon="User"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password" class="input">
            <el-input
              v-model="formModel.password"
              name="password"
              :prefix-icon="Lock"
              type="password"
              show-password
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="login" class="button" type="primary" auto-insert-space
              >登录</el-button
            >
          </el-form-item>
          <el-form-item class="flex">
            <el-link type="info" :underline="false" @click="isRegister = false"> 注册 → </el-link>
          </el-form-item>
        </div>
        <h6>
          本科生实践信息发布平台&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@领航工作室出品
        </h6>
      </el-form>
      <!-- 注册相关表单 -->
      <el-form
        v-else
        ref="form"
        :model="formModel"
        :rules="rules"
        size="large"
        autocomplete="off"
        class="form"
      >
        <!-- v-else -->
        <el-form-item class="title">
          <div>
            <h1>欢迎注册</h1>
          </div>
        </el-form-item>
        <div class="form-data">
          <el-form-item prop="name" class="input">
            <el-input
              v-model="formModel.name"
              :prefix-icon="User"
              placeholder="请输入姓名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="work_num" class="input">
            <el-input
              v-model="formModel.work_num"
              :prefix-icon="User"
              placeholder="请输入工号"
            ></el-input>
          </el-form-item>
          <el-form-item prop="account" class="input">
            <el-input
              v-model="formModel.account"
              :prefix-icon="User"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password" class="input">
            <el-input
              v-model="formModel.password"
              name="password"
              :prefix-icon="Lock"
              type="password"
              show-password
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item prop="rePassword" class="input">
            <el-input
              v-model="formModel.rePassword"
              :prefix-icon="Lock"
              type="password"
              show-password
              placeholder="请再次输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item>  
            <el-button @click="register" class="button" type="primary" auto-insert-space
              >注册</el-button
            >
          </el-form-item>
          <el-form-item class="return">
            <el-link type="info" :underline="false" @click="isRegister = true"> ← 登录 </el-link>
          </el-form-item>
        </div>
        <h6>本科生实践信息发布平台&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h6>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  background-image: url(@/assets/background-Img.jpg);
  background-size: cover;
  height: 100vh;
  display: flex;
  align-items: center;
  .form {
    background-color: white;
    user-select: none;
    border-radius: 15px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .title {
      text-align: left;
      margin-top: 20px;
      width: 300px;
    }
    .form-data {
      width: 300px;
      height: auto;
    }

    .input {
      justify-content: center;
    }

    .button {
      width: 100%;
      justify-content: center;
    }
    .flex {
      width: 100px;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
